//
//  CCAPulbicViewModel.m
//  Activity
//
//  Created by its on 15/5/11.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCAPublicViewModel.h"
#import "CCError.h"
#import "CCAPublicModel.h"
#import <AVOSCloud/AVOSCloud.h>
#import <RXPromise/RXPromise.h>
#import <RXPromise/RXPromise+RXExtension.h>

@interface CCAPublicViewModel()
@property (nonatomic, assign) CGFloat tileHeight;
@property (nonatomic, strong) CCAPublicModel *model;
@end

@implementation CCAPublicViewModel

- (id) initWithModel:(CCAPublicModel *)model {
  if (self = [super init]) {
    _tileHeight = [self setTitleLineNumber:@"标\n题" font:[UIFont boldSystemFontOfSize: 19]];
    _imageArray = [NSMutableArray array];
  }
  return self;  
}

- (void) bindModel {
  RAC(_model, title) = RACObserve(self, title);
  RAC(_model, startDate) = RACObserve(self, startDate);
  RAC(_model, endDate) = RACObserve(self, endDate);
  RAC(_model, people) = RACObserve(self, people);
  RAC(_model, address) = RACObserve(self, address);
  RAC(_model, content) = RACObserve(self, content);
  RAC(_model, imageArray) = RACObserve(self, imageArray);
}

- (CGFloat) setTitleLineNumber:(NSString *) text font:(UIFont *) font {
  CGRect rect = [text boundingRectWithSize:CGSizeMake(300, 1000)
                                   options:NSStringDrawingUsesLineFragmentOrigin
                                attributes:@{NSFontAttributeName:font} context:nil];
  return rect.size.height + 5;
}

- (RACSignal *) titleHeight:(NSString *)str font:(UIFont *)font {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    CGFloat height = [self setTitleLineNumber:str font:font];
    [subscriber sendNext: @((height <= self.tileHeight)?height: self.tileHeight)];
    [subscriber sendCompleted];
    return [RACDisposable disposableWithBlock:^{
      
    }];
  }];
}

- (RACSignal *) publicActivity {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    RACCompoundDisposable *dispose = [RACCompoundDisposable compoundDisposable];
    if (_imageArray.count == 0) {
      [subscriber sendNext:[CCError errorWithCode:1 des:@"至少添加一张图片"]];
    } else if([_title isEqualToString:@"标题"]){
      [subscriber sendNext:[CCError errorWithCode:2 des:@"请添加标题"]];
    } else if ([_startDate isEqualToString:@"开始时间"]) {
      [subscriber sendNext:[CCError errorWithCode:3 des:@"请选择开始时间"]];
    } else if ([_endDate isEqualToString:@"结束时间"]) {
      [subscriber sendNext:[CCError errorWithCode:5 des:@"请选择结束时间"]];
    } else if (_content.length == 0) {
      [subscriber sendNext:[CCError errorWithCode:5 des:@"请填写活动内容"]];
    } else {
      [subscriber sendNext:[CCError errorWithCode:10 des:@"请等待"]];
      RACDisposable *publicDisposable = [[_model publicActivity] subscribeNext:^(CCError *x) {
        [subscriber sendNext:x];
      } completed:^{
        
      }];
      [dispose addDisposable:publicDisposable];
    }
    return dispose;
  }];
}
@end
